<template>
  <view class="moisture-report-container">
    <!-- 使用up-form组件实现表单 -->
    <up-form
      ref="formRef"
      label-position="left"
      :model="formData"
      label-width="auto"
      :rules="rules"
    >
      <!-- 饲料类型 -->
      <up-form-item
        label="饲料类型："
        prop="feedType"
        :border-bottom="true"
        @click="showFeedType = true; hideKeyboard()"
      >
        <up-input
          v-model="formData.feedType"
          disabled
          placeholder="请选择饲料类型"
          border="none"
        />
        <template #right>
          <up-icon name="arrow-right" />
        </template>
      </up-form-item>

      <!-- 批号 -->
      <up-form-item
        label="混合批次："
        prop="batchNumber"
        :border-bottom="true"
      >
        <up-input
          v-model="formData.batchNumber"
          type="digit"
          placeholder="请输入混合批次"
          border="none"
        />
      </up-form-item>

      <!-- 检测时间 -->
      <up-form-item
        label="检测时间："
        prop="detectionTime"
        :border-bottom="true"
        @click="showDateTimePicker = true; hideKeyboard()"
      >
        <up-input
          v-model="formData.detectionTime"
          disabled
          placeholder="请选择检测时间"
          border="none"
        />
        <template #right>
          <up-icon name="arrow-right" />
        </template>
      </up-form-item>

      <!-- 含水率 -->
      <up-form-item
        label="含水率(%)："
        prop="moistureContent"
        :border-bottom="true"
      >
        <up-input
          v-model="formData.moistureContent"
          type="digit"
          placeholder="输入含水率"
          border="none"
          suffix="%"
        />
      </up-form-item>
    </up-form>

    <!-- 提交按钮 -->
    <view class="submit-container">
      <up-button
        class="submit-button"
        type="primary"
        :plain="false"
        :hairline="false"
        @click="submitForm"
      >
        提交检测数据
      </up-button>
    </view>

    <!-- 饲料类型选择器 -->
    <up-action-sheet
      :show="showFeedType"
      :actions="feedTypeActions"
      title="请选择饲料类型"
      @close="showFeedType = false"
      @select="feedTypeSelect"
    />

    <!-- 批号选择器 -->
    <up-action-sheet
      :show="showBatchNumber"
      :actions="batchNumberActions"
      title="请选择批号"
      @close="showBatchNumber = false"
      @select="batchNumberSelect"
    />

    <!-- 日期选择器 -->
    <up-datetime-picker
      v-model="currentDate"
      :show="showDateTimePicker"
      mode="datetime"
      :min-date="oneWeekAgo"
      :formatter="formatter"
      confirm-color="#07c160"
      @confirm="dateConfirm"
      @cancel="showDateTimePicker = false"
    />
  </view>
</template>

<script setup lang="ts">
import type { DictPageListRes } from '@/api/common/types';
import type { AddMoistureInfoRes, MoistureData } from '@/api/moisture/types';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import { computed, reactive, ref } from 'vue';
import { getDictPageList } from '@/api/common';
import { addMoistureInfo } from '@/api/moisture';
import { useUserStore } from '@/store';

const userStore = useUserStore();

dayjs.extend(customParseFormat);

const currentDate = ref(new Date());
// 获取当前日期并格式化为YYYY-MM-DD格式
const getCurrentDate = () => {
  const now = currentDate.value;
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

// 表单数据模型
const formData = reactive({
  feedType: '',
  batchNumber: 1, // 默认选中第一个批次
  detectionTime: getCurrentDate(), // 默认当前日期
  moistureContent: '',
});

// 表单验证规则
const rules = reactive({
  feedType: [
    {
      required: true,
      message: '请选择饲料类型',
      trigger: 'change',
    },
  ],
  batchNumber: [
    {
      required: true,
      message: '请输入混合批次',
      trigger: 'change',
    },
    {
      validator: (rule: any, value: string, callback: (error?: string) => void) => {
        if (!value || Number.isNaN(Number(value))) {
          callback('请输入有效的混合批次');
        }
        else if (Number(value) < 0 || Number(value) > 100) {
          callback('含水率应在0-100之间');
        }
        else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
  detectionTime: [
    {
      required: true,
      message: '请选择检测时间',
      trigger: 'change',
    },
  ],
  moistureContent: [
    {
      required: true,
      message: '请输入含水率',
      trigger: 'blur',
    },
    {
      validator: (rule: any, value: string, callback: (error?: string) => void) => {
        if (!value || Number.isNaN(Number(value))) {
          callback('请输入有效的含水率');
        }
        else if (Number(value) < 0 || Number(value) > 100) {
          callback('含水率应在0-100之间');
        }
        else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
});

// 表单引用
const formRef = ref<any>();

// 选择器显示状态
const showFeedType = ref(false);
const showBatchNumber = ref(false);
const showDateTimePicker = ref(false);

// 计算一周前的日期
const oneWeekAgo = computed(() => {
  const date = new Date();
  date.setDate(date.getDate() - 7);
  return date.getTime();
});

// 饲料类型选项
const feedTypeActions = ref<DictPageListRes[]>([
  { name: '进口苜蓿', value: '进口苜蓿' },
  { name: '青贮', value: '青贮' },
  { name: '玉米', value: '玉米' },
  { name: '大豆饼', value: '大豆饼' },
  { name: '麦麸', value: '麦麸' },
  { name: '秸秆', value: '秸秆' },
]);

// 字典列表
// const dictList = ref<DictPageListRes[]>([]);

const getDictList = async () => {
  const res: any = await getDictPageList({
    current: 1,
    pageSize: 100,
    tagId: 398162,
  });
  const feedTypes = res.data.map((item: DictPageListRes) => {
    return {
      name: item.value || '',
      value: item.name || '',
    };
  });
  feedTypeActions.value = feedTypes;
};

// 批号选项
const batchNumberActions = [
  { name: '批次20230910-001', value: '批次20230910-001' },
  { name: '批次20230909-002', value: '批次20230909-002' },
  { name: '批次20230908-003', value: '批次20230908-003' },
  { name: '批次20230907-001', value: '批次20230907-001' },
];

// 日期格式化函数
function formatter(type: string, value: number) {
  if (type === 'year') {
    return `${value}年`;
  }
  if (type === 'month') {
    return `${value}月`;
  }
  if (type === 'day') {
    return `${value}日`;
  }
  return value;
}

// 隐藏键盘
function hideKeyboard() {
  uni.hideKeyboard();
}

// 饲料类型选择
function feedTypeSelect(action: any) {
  formData.feedType = action.name;
  showFeedType.value = false;
}

// 批号选择
function batchNumberSelect(action: any) {
  formData.batchNumber = action.name;
  showBatchNumber.value = false;
}

function dateConfirm(e: any): any {
  showDateTimePicker.value = false;
  formData.detectionTime = dayjs(e.value).format('YYYY-MM-DD HH:mm:ss');
  formRef.value.validateField('detectionTime');
}

// 提交表单
async function submitForm() {
  try {
    await formRef.value.validate();
    // 表单验证通过，提交数据
    console.log('表单验证通过，提交数据:', formData);
    // 模拟提交数据
    const submitData: MoistureData = {
      feedType: formData.feedType,
      batchNumber: Number(formData.batchNumber).toFixed(0),
      detectionTime: formData.detectionTime,
      detectionPerson: userStore.name || '',
      moistureContent: Number(formData.moistureContent),
    };

    console.log('提交的表单数据:', submitData);

    // 显示提交成功提示
    uni.showLoading({
      title: '提交中...',
    });
    // 提交数据
    const res: AddMoistureInfoRes = await addMoistureInfo(submitData);
    if (res.code === 200) {
      uni.hideLoading();
      uni.showToast({
        title: '提交成功',
      });

      formRef.value.resetFields();
      // 可以选择是否清空表单
    // formData.moistureContent = '';
    }
    else {
      uni.hideLoading();
      uni.showToast({
        title: res.msg || '提交失败',
        icon: 'none',
      });
    }
  }
  catch {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'none',
    });
  }
}

onShow(() => {
  getDictList();
});
</script>

<style scoped lang="scss">
.moisture-report-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding: 0 30rpx;
}

.submit-container {
  padding: 30rpx 0;
}

.submit-button {
  height: 90rpx;
  font-size: 32rpx;
  font-weight: 600;
  background-color: #07c160;
  border-radius: 10rpx;
}

// 覆盖uview-plus组件样式
::v-deep(.up-form-item__label) {
  font-size: 28rpx;
  color: #666666;
}

::v-deep(.up-input__placeholder) {
  font-size: 28rpx;
  color: #c0c4cc;
}

::v-deep(.up-input__inner) {
  font-size: 28rpx;
  color: #333333;
}

::v-deep(.up-action-sheet__actions-item) {
  font-size: 28rpx;
  color: #333333;
}
</style>
